package com.szkiti.myautils.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
 * SharedPreferences管理类
 * 
 */
public class SettingManager {
	
	private SharedPreferences settings = null;
	
	private static SettingManager instance=null;
	
	private SettingManager () {
		
	}

	public static SettingManager getInstance() {
		if (instance == null) {
			instance = new SettingManager();
		}
		return instance;
	}
	
	/**
	 * 初始化设置
	 * 
	 * @param context
	 */
	public  void initialize(Context context) {
		settings = PreferenceManager.getDefaultSharedPreferences(context);
	}

	/**
	 * 写操作,写完并commit
	 * 
	 * @param name
	 * @param obj
	 */
	public void writeSetting(String name, Object obj) {
		SharedPreferences.Editor editor = settings.edit();
		if (obj instanceof Boolean) {
			editor.putBoolean(name, (Boolean) obj);
		}
		else if (obj instanceof Integer) {
			editor.putInt(name, (Integer) obj);
		}
		else if (obj instanceof Float) {
			editor.putFloat(name, (Float) obj);
		}
		else if (obj instanceof Long) {
			editor.putLong(name, (Long) obj);
		}
		else if (obj instanceof String) {
			editor.putString(name, (String) obj);
		}
		editor.commit();
	}

	/**
	 * 清除掉已经有得设置
	 * 
	 * @param name
	 */
	public void deleteSetting(String name) {
		SharedPreferences.Editor editor = settings.edit();
		editor.remove(name);
		editor.commit();
	}
	
	public Object readSetting(String name, Object res, Object defaultValue) {
		if (res instanceof Boolean) {
			res = settings.getBoolean(name, (Boolean) defaultValue);
		} else if (res instanceof Integer) {
			res = settings.getInt(name, (Integer) defaultValue);
		} else if (res instanceof Float) {
			res = settings.getFloat(name, (Float) defaultValue);
		} else if (res instanceof Long) {
			res = settings.getLong(name, (Long) defaultValue);
		} else if (res instanceof String) {
			res = settings.getString(name, (String) defaultValue);
		} 
		return res;
	}
}